﻿using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;


namespace SBlogCore.Common.DatabaseAccessor.Extend
{
    [SkipScan]
    public static class DatabaseAccessorExtensions
    {
        public static void AddGlobalDbContextSetUp(this IServiceCollection services)
        {
            services.AddDbContextPool<GlobalDbContext>(
           options => options
           .UseSqlServer(AppSetting.ReadAppSettings("ConnectionStrings:SBlogCore"),x => x.MigrationsAssembly("SBlogCore.EntityFrameworkContext"))
           .LogTo(Console.WriteLine));
        }
        /// <summary>
        /// 数据库迁移
        /// TODO：不存在会创建新的数据库
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static async Task UseMigrateDataBaseAsync(this IApplicationBuilder builder)
        {
            var context = builder.ApplicationServices.GetService<GlobalDbContext>();
            if (context!=null&&context.Database.IsSqlServer())
                await context.Database.MigrateAsync();
        }
    }
}
